import React, {useState,useEffect} from "react";
import Modal from "antd/lib/modal";
import Form from "antd/lib/form";
import Select from 'antd/lib/select';
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {UserProfile} from "@/components/proptypes";
import EmployeeActivity from "@/services/employeeactivity";
import notification from "@/services/notification";
import {currentUser} from "@/services/auth";
import moment from "moment";
import DatePicker from "antd/lib/date-picker";
import locale from 'antd/es/date-picker/locale/zh_CN';
import 'braft-editor/dist/index.css';
import BraftEditor from 'braft-editor';
import Customer from "@/services/customer";

const mwidth=document.querySelector('body').offsetWidth*0.4
const excludeControls = [ 'undo', 'redo', 'separator','line-height','letter-spacing','superscript', 'italic', 'subscript',
'remove-styles','emoji','link','list-ul','list-ol','media','headings', 'blockquote', 'code',
 'hr', 'clear','font-size']

function CreateFollowUpDialog({ employeeactivityid,employeeid,sourcetype, dialog }) {
  const [dataLoaded, setDataLoaded] = useState(false);
  const [message, setmessage] = useState("");
  const [created_at, setcreated_at] = useState(moment());
  const [userid, setuserid] = useState(currentUser.id);
  const [employeeuserdata, setemployeeuserdata] = useState([]);
 
  const isCreateStateEnabled = useState(true);

  useEffect(() => {
    if(employeeactivityid>0){
        EmployeeActivity.get({id: employeeactivityid}).then(data => {
            setmessage(BraftEditor.createEditorState(data.message)); 
            setcreated_at(moment(data.created_at));
            setuserid(data.userid)
            setDataLoaded(true);
          });
    }else{
        setDataLoaded(true);
    }
  }, [employeeactivityid]);
  useEffect(() => {
    Customer.querycustomeruser({ code: "", name: "", userid: currentUser.id, }).then(data => {
      setemployeeuserdata(data);
    });
  }, []);


  function handlemessageChange(event) {
    //const value = trim(event.target.value);
    setmessage(event);
  }
  function handleSubmit() {

      const htmlContent = message.toHTML()
      if(htmlContent.length<1){
        notification.error("跟进内容不能为空！");
        return ;
      }
      if(currentUser.id !==userid){
        notification.error("不能修改其他跟进人的信息！");
        return ;
      }
     let data={id: employeeactivityid,//
              userid: currentUser.id,//--操作员ID
              type:0,
              employeeid:employeeid,
              message: htmlContent,
              sourcetype: sourcetype,}
      if(employeeactivityid===0) {
        EmployeeActivity.create(data)
          .then(() => {
            dialog.close({ success: true});
          })
          .catch(error => {
            notification.error(error.message, error.detailedMessage);
          });
      }else{
        EmployeeActivity.save(data)
          .then(() => {
            dialog.close({ success: true});
          })
          .catch(error => {
            notification.error(error.message, error.detailedMessage);
          });
      }
    dialog.close({success:true});
  }

  return (
    <Modal
      {...dialog.props}
      {...(isCreateStateEnabled ? {} : { footer: null })}
      width={document.querySelector('body').offsetWidth*0.4}
      title="跟进信息"
      okText="确定"
      cancelText="取消"

      onOk={handleSubmit}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      {dataLoaded && (
      <DynamicComponent name="CreateFollowUpDialogExtra" >
      <Form>
        <Form.Item style={{ marginBottom: 10 }} label="跟进内容">
          <BraftEditor
                    value={message}
                    excludeControls={excludeControls}
                    onChange={handlemessageChange}
                    // onSave={submitContent}
                    contentStyle={{height: 250, minHeight: 200,width: mwidth, minWwidth: mwidth}}
                />
        </Form.Item>
        <Form.Item style={{ marginBottom: 10 }} label="跟   进   人">
            <Select style={{ width: "200px" }}
                  showSearch
                  disabled={true}
                  optionFilterProp="children"
                  value={userid}
                  >
                  {(employeeuserdata || []).map(item => (
                    <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                  ))}
                </Select>
        </Form.Item>
        <Form.Item style={{ marginBottom: 10 }} label="跟进时间">
            <DatePicker
                locale={locale}
                style={{ width:  200 }}
                value={created_at}
                placeholder="日期"
                disabled ={true}
                autoFocus
            />
        </Form.Item>

      </Form>
      </DynamicComponent>
      )}
    </Modal>
  );
}

CreateFollowUpDialog.propTypes = {
  annex_id: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateFollowUpDialog);
